<?php

namespace app\admin\model;

class Nav extends Base
{
    /**
     * @return array
     * 数据验证规则
     */
    public function filedRules(){
        return [
            "action"=>["add","update","status","delete"],
            "form"=>[
                'id|id|用户ID|update|status|delete' => 'require',
                'nav|nav|菜单名称|add|update'=>'require',
                'nav_url|nav_url|菜单链接|add|update'=>'normal',
                'nid|nid|菜单id|add|update'=>'require',
                'sort|sort|排序|add|update'=>'normal',
                'status|status|用户状态|add|update|status'=>'require|number',
            ],
        ];
    }
    /**
     * 获取登录用户的所有权限id和路由
     */
    public function getRuleIds(){
        $admin=session("admin");
        $where[]=["id","in",$admin["role_ids"]];
        $where[]=["is_del","=","0"];
        $where[]=["status","=","1"];
        $roleArr=getDbAll("role",$where);
        $roleIds=[1];
        if($roleArr){
           foreach ($roleArr as $k=>$v){
               if($v["role"]=="*"){
                   $navIds=array_column(getDbAll("nav",[],"","","id"),"id");
                   $roleIds=array_merge($roleIds,$navIds);
               }else{
                   if($v["role"]) $roleIds=array_merge($roleIds,explode(",",$v["role"]));
               }
           }
        }
        return array_unique($roleIds);
    }
    /**
     * 获取所有一二级菜单用于后台左边菜单栏目展示
     */
    public function getNavList($ruleIds=[]){
        $where[]=["is_del","=","0"];
        if($ruleIds) $where[]=["id","in",$ruleIds];
        $omenu = getDbAll("nav",array_merge($where,[["nid","=","0"]]),"sort asc");
        if($omenu){
            foreach(@$omenu as $key => $val) {
                $omenu[$key]['wmenu'] = getDbAll("nav",array_merge($where,[["nid","=",$val["id"]]]),"sort asc");
                if($omenu[$key]['wmenu']){
                    foreach ($omenu[$key]['wmenu'] as $m=>$n){
                        $omenu[$key]['wmenu'][$m]['three']=getDbAll("nav",array_merge($where,[["nid","=",$n["id"]]]),"sort asc");
                    }
                }
            }
        }
        return $omenu;
    }
    /**
     * 获取主菜单下面的一二级菜单
     */
    public function getNavChild($data){
        if($data && is_array($data)){
            foreach($data as $key => $val) {
                $data[$key]['wmenu'] = getDbAll("nav",["nid"=>$val["id"],"is_del"=>0],"sort asc");
                if(!empty($data[$key]['wmenu'])){
                    foreach ($data[$key]['wmenu'] as $k => $v){
                        $data[$key]['wmenu'][$k]['three'] = getDbAll("nav",["nid"=>$v["id"],"is_del"=>0],"sort asc");
                    }
                }
            }
        }
        return $data;
    }
}